// 生产环境 Webpack 配置
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin  = require("css-minimizer-webpack-plugin");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;
const TerserPlugin = require("terser-webpack-plugin");

// 自定义插件配置
const customerPlugins =  common.plugins.map(plugin => {
    if(plugin instanceof HtmlWebpackPlugin){
        return new HtmlWebpackPlugin({
            ...plugin.options,
            minify: {
                collapseWhitespace: true, // 折叠空白区域(空格、制表符、换行符)为单个空格
                removeComments: true, // 移除HTML中的所有注释（包括条件注释，注意：如果注释中包含重要信息（如IE条件注释），需谨慎使用）
                removeAttributeQuotes: false, // 移除属性的引号，不建议，可能会破坏特殊字符的属性值
                minifyCSS: true, // 压缩内联css
                minifyJS: true, // 压缩内联js
                minifyURLs: true, // 压缩内联URLs
                removeRedundantAttributes: true, // 移除冗余的属性，例如：<input type="text" name="name"> 可以简化为 <input name="name">
                useShortDoctype: true, // 使用短文档类型（<!DOCTYPE html>）
            }
        })
    }
    return plugin;
})
customerPlugins.push( new MiniCssExtractPlugin({
    filename: 'assets/css/[name]-[contenthash].css',
    chunkFilename: 'assets/css/[id]-[contenthash].css'
}))

customerPlugins.push(new BundleAnalyzerPlugin({
    analyzerMode: 'static', // 生成静态报告
    analyzerPort: 8081, // 分析器端口
    reportFilename: 'bundle-report.html', // 报告文件名
    openAnalyzer: false, // 不自动打开浏览器
    generateStatsFile: true, // 生成stats.json文件
    statsFilename: 'stats.json' // stats文件名称
}))

module.exports = merge(common, {
    mode: "production",
    devtool: 'source-map',
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
            },
            {
                test: /\.scss$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader']
            },
            {
                test: /\.less$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader' , 'postcss-loader', {
                    loader: "less-loader",
                    options: {
                        lessOptions: {
                            javascriptEnabled: true
                        }
                    }
                }]
            },
            {
                test: /\.(png|jpe?g|gif|svg)$/i,
                type: 'asset/resource',
                use: [
                    {
                        loader: 'image-webpack-loader',
                        options: {
                            mozjpeg: { progressive: true, quality: 65 }, // JPEG 压缩
                            optipng: { enabled: false }, // 禁用 PNG 优化（使用 pngquant 替代）
                            pngquant: { quality: [0.65, 0.9], speed: 4 }, // PNG 压缩
                            gifsicle: { interlaced: false }, // GIF 优化
                            webp: { quality: 75 } // 生成 WebP 格式（需浏览器支持）
                        }
                    }
                ],
                generator: {
                    filename: 'assets/images/[name]-[hash][ext]'
                }
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/i,
                type: 'asset/resource',
                generator: {
                  filename: 'assets/fonts/[name][ext]'
                }
            }
        ]
    },
    plugins: customerPlugins,
    optimization: {
        minimize: true, // 启用压缩
        minimizer: [
            new CssMinimizerPlugin({
                minimizerOptions: {
                    preset: ['default', { discardComments: { removeAll: true } }]
                },
                parallel: true
            }),
            new TerserPlugin({
                parallel: true, // 启用多线程
                terserOptions: {
                    compress: {
                        drop_console: true, // 移除console‘
                    }
                }
            })
        ],
        splitChunks: {
            chunks: 'all',
            minSize: 30000, // 最小30KB才拆分
            maxSize: 244000, // 最大244KB尝试拆分
            minChunks: 1,
            maxAsyncRequests: 5,
            maxInitialRequests: 3,
            automaticNameDelimiter: '~',
            cacheGroups: {
                polyfills: {
                    test: /[\\/]node_modules[\\/](core-js|@babel\/runtime|regenerator-runtime)[\\/]/,
                    name: 'polyfills',
                    priority: 20,
                    enforce: true,
                    chunks: 'all'
                },
                vendors: {
                    test: /[\\/]node_modules[\\/]/,
                    name(module) {
                        // 按node_modules中的包名拆分
                        const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
                        return `vendors.${packageName.replace('@', '')}`;
                    },
                    priority: 10,
                    reuseExistingChunk: true
                },
                default: {
                    minChunks: 2,
                    priority: -20,
                    reuseExistingChunk: true
                }
            }
        },
        runtimeChunk: {
            name: 'runtime'
        }
    }
})